package com.cinema.api.controller;


import com.cinema.api.constant.Roles;
import com.cinema.api.model.entity.User;
import com.cinema.api.model.vo.LoginVO;
import com.cinema.api.service.UserService;
import com.cinema.api.utils.JwtUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xhh
 * @since 2021-12-31
 */
@Slf4j
@Api(tags = "用户接口")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("/login")
    @ApiOperation("普通用户登录")
    public Map<String, Object> login(@RequestBody LoginVO loginVO) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        // 校验并返回登录用户的信息
        User user = userService.getLogin(loginVO);
        // 是否记住我？（Token过期时间：一个星期&一天）
        long exp = loginVO.isRemember() ? JwtUtil.REMEMBER_EXPIRATION_TIME : JwtUtil.EXPIRATION_TIME;
        // 分配权限
        List<String> roles = new ArrayList<>();
        roles.add(Roles.ROLE_USER);
        // 返回用户信息及token
        map.put("token", JwtUtil.createToken(loginVO.getUsername(), roles, exp));
        map.put("user", user);
        return map;
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public void register(@RequestBody User user) throws Exception {
        userService.register(user);
    }

    @GetMapping("")
    @PreAuthorize("hasAnyRole('ROLE_FIND_USER')")
    @ApiOperation(value = "查找所有用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value="页码", paramType = "query" ,required = true, defaultValue = "1"),
            @ApiImplicitParam(name = "limit", value="每页条数", paramType = "query",required = true, defaultValue = "10"),
    })
    public List<User> findAll() {
        return userService.findAll();
    }

    @GetMapping("/page")
    @PreAuthorize("hasAnyRole('ROLE_FIND_USER')")
    @ApiOperation(value = "分页查找所有用户")
    public PageInfo<User> findAllByPage(@RequestParam int page, @RequestParam int limit) {
        return userService.findAllByPage(page, limit);
    }

    @GetMapping("/like")
    @PreAuthorize("hasAnyRole('ROLE_FIND_USER')")
    @ApiOperation(value = "根据用户名模糊查询-分页查找所有用户")
    public PageInfo<User> findByLike(@RequestParam Map<String, Object> params) {
        int page = Integer.parseInt(params.get("page").toString());
        int limit = Integer.parseInt(params.get("limit").toString());
        String username = (String) params.get("username");
        return userService.findByLike(page, limit, username);
    }

    @GetMapping("/findByUserName")
    @ApiOperation(value = "根据用户名以及电话查找用户")
    public User findByUserName(@RequestParam String username, @RequestParam String phone) {
        return userService.findByNameAndPhone(username, phone);
    }

    @PreAuthorize("hasAnyRole('ROLE_ADMIN')")
    @PutMapping("")
    @ApiOperation(value = "更新用户信息")
    public void updateUser(@RequestBody User user) {
        userService.updateUser(user);
    }

    @PostMapping("/reset")
    @ApiOperation(value = "根据用户名更新用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", paramType = "query"),

    })
    public void reset(@RequestBody Map<String, String> params) {
        String phone = params.get("phone");
        String username = params.get("username");
        String password = params.get("password");
        userService.reset(username, password);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据Id查找用户")
    public User findById(@PathVariable String id) {
        return userService.findById(id);
    }
}
